<template>
  <view class="viewport">
    <view class="logo">
      <image src="../../static//images/Books/book_2.png"></image>
    </view>
    <view class="login">
      <button type="primary" @tap="onWxLogin">
        <text class="icon icon-phone"></text>
        微信一键快捷登录
      </button>
      <view class="extra">
        <view class="caption">
          <text>其他登录方式</text>
        </view>
        <view class="options">
          <!-- 通用登录 -->
          <button @tap="onLoginByAccountAndPassword">
            <text class="icon icon-phone"
              >教师或用户账号密码登录(点击登录)</text
            >
          </button>
          <uni-easyinput
            v-model="loginMessage.account"
            focus
            placeholder="请输入账号"
          ></uni-easyinput>
          <uni-easyinput
            v-model="loginMessage.password"
            focus
            placeholder="请输入密码"
          ></uni-easyinput>
          <!-- 是否是教师 -->
          <uni-card is-full>
            <uni-section title="我是管理员：" type="line">
              <view class="uni-px-5 uni-pb-5">
                <uni-data-checkbox
                  v-model="loginMessage.isTeacher"
                  :localdata="yesOrNoCandidates"
                ></uni-data-checkbox>
              </view>
            </uni-section>
          </uni-card>

          <!-- 显示 dev -->
          <button
            v-if="false"
            @tap="
              () => {
                console.log(loginMessage);
              }
            "
          >
            显示loginMessage
          </button>
        </view>
      </view>
      <view class="tips"
        >登录/注册即视为你同意《服务条款》和《电子图书馆平台隐私协议》</view
      >
    </view>
  </view>
</template>

<script setup lang="ts">
// 登录按钮的回调函数
import { postLoginByAccountAndPassword } from "@/services/login";
import { useMemberStore } from "@/stores";
import type { LoginResultUserVO, LoginDTO } from "@/types/member";
import { wxloginGetCode, wxloginApi } from "@/api/oauth/custom/customlogin";
import { getUserInfo } from "@/api/auth/user";
import { ref } from "vue";
/**
 * 登录成功后执行的操作
 */
const onLoginSucess = async (profile: LoginResultUserVO) => {
  // 保存用户信息
  const useMember = useMemberStore();
  useMember.setProfile(profile);

  // MARK 获取用户详细信息
  var userInfo = (await getUserInfo()).data;
  profile.name = userInfo.name;
  profile.avatar = userInfo.avatar;
  // 更新用户信息
  // MARK uni的持久不支持更新
  useMember.clearProfile();
  useMember.setProfile(profile);

  uni.showToast({
    title: "登录成功",
    icon: "success",
  });
  setTimeout(() => {
    uni.switchTab({
      url: "/pages/my/my",
    });
  }, 800);
};

/**
 * 微信一键登录
 * 微信登录
 * 设置微信登录的code，准备发送给后端
 */
let code = ref("");
let loginDto = ref({
  password: "",
  username: "",
  wxCode: "",
  authType: "weixin",
});

const onWxLogin = async () => {
  // 微信login的回调方式和本身函数的执行方式存在一定bug，无法正常的await，建议把登录逻辑全部写道login中
  let res = await wxloginGetCode();
  console.log("用户进行登录，获得回调参数res：", res);
  code.value = res.code;
  console.log("获取到的code: ", code.value);
  loginDto.value.wxCode = code.value;
  // 执行登录逻辑
  try {
    let oauthResult = await wxloginApi(loginDto.value);
    let profile = {
      /** 用户ID */
      id: "",
      // 基础信息
      name: "", // -姓名
      account: "", //-账户
      password: "", //-密码
      phone: "", //-电话号码
      avatar: "", //-头像
      openid: "" /** 微信openid */,
      authorization: oauthResult.access_token,
    };
    console.log("本地用户信息profile:", profile);
    // TODO 获取用户的个人信息，填充进入profile
    // 执行成功操作
    await onLoginSucess(profile);
  } catch (error) {
    uni.showToast({
      title: "登录失败",
      icon: "error",
    });
  }
};

let loginMessage = ref<LoginDTO>({
  account: "",
  password: "",
  isTeacher: false,
});
//MARK 账号密码登录-- 废弃
const onLoginByAccountAndPassword = async () => {
  if (loginMessage.value.isTeacher == null) {
    uni.showToast({
      title: "未选择登录角色",
      icon: "error",
    });
  }

  console.log("loginMessage: ", loginMessage);
  try {
    let profile = await postLoginByAccountAndPassword(loginMessage.value);
    console.log("本地用户信息profile:", profile);
    // 执行成功操作
    onLoginSucess(profile.data);
  } catch (error) {
    uni.showToast({
      title: "登录失败",
      icon: "error",
    });
  }
};

// 设置isTeacher
let yesOrNoCandidates = [
  {
    text: "否",
    value: 0,
  },
  {
    text: "是",
    value: 1,
  },
];
const setIsTeacher = () => {};
</script>

<style lang="scss">
page {
  height: 100%;
  align-items: center;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 20rpx;
}

.logo {
  text-align: center;
  margin: 0%;
  padding: 0%;
  image {
    width: 250rpx;
    height: 250rpx;
  }
}

.login {
  display: flex;
  flex-direction: column;
  text-align: center;
  padding: 40rpx 20rpx 20rpx;

  .input {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    border: 1px solid #ddd;
    padding-left: 30rpx;
    margin-bottom: 20rpx;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;
    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #28bb9c;
  }

  .wechat {
    background-color: #06c05f;
  }

  .extra {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text-align: center;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;
      button {
        padding: 0;
        background-color: transparent;
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}
</style>
